package com.yzh.wanandroid.component.fragment

import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.CollectionAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentCollectionBinding
import com.yzh.wanandroid.vm.CollectionFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *  收藏页面
 */
class CollectionFragment : MvvmFragment<FragmentCollectionBinding,CollectionFragmentVm>() {

    private val TAG = "CollectionFragment"

    private val mAdapter by lazy { CollectionAdapter() }

    override fun initViewModel(): CollectionFragmentVm = createViewModel()

    override fun getLayoutId() = R.layout.fragment_collection

    override fun initView(view: View) {
        initBinding()
        initTitleBar()
        initRecyclerView()
        initSwipeRefresh()
    }

    private fun initBinding() {
        mBinding.run {
            adapter = mAdapter
            refreshData = mAdapter.refreshData
        }
    }

    private fun initTitleBar() {
        mBinding.run {
            collectTitleLayout.titleText.setText(R.string.nav_my_collect)
            collectTitleLayout.toolbar.navigationIcon = requireActivity().getDrawable(R.drawable.arrow_back)
            collectTitleLayout.toolbar.setNavigationOnClickListener {
                requireActivity().onBackPressed()
            }
        }
    }

    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(requireActivity())
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            collectList.layoutManager = linearLayoutManager
        }
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private fun initSwipeRefresh() {
        mBinding.run {
            collectSwipeRefresh.setColorSchemeResources(R.color.color_main)
            collectSwipeRefresh.setOnRefreshListener { initData() }
        }
    }

    override fun initData() {
        loadArticleData()
    }

    private fun loadArticleData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData().collectLatest {
                    mAdapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}